import { AiOutlineCloseCircle } from 'react-icons/ai';
import React, { ReactNode, useState, useEffect } from 'react';
import cls from './index.module.less';
import { InputNumber, Space, Typography, Modal, Button } from 'antd';
import { CheckBox } from 'devextreme-react';
import { model } from '@/ts/base';
import VariableMapping from '@/components/Common/FlowDesign/Config/Rule/modal/VariableMapping';
import ButtonConfig from './buttonConfig';
import { IWork } from '@/ts/core';

type ShareShowRecentProps = {
  departData: { name: string; id: string; type?: string }[];
  deleteFuc: (id: string) => void;
  onClick?: Function;
  tags?: (id: string) => ReactNode;
};

const DataModal = (props:{operateRule: any, departData: any, isOpen: boolean, onClose: () => void}) => {
  const [mappingData, setMappingData] = useState<model.MappingData[]>(props.operateRule.showChangeData ?? []);
  const [triggers, setTriggers] = useState<model.MappingData[]>([]);

  useEffect(() => {
    const tgs: model.MappingData[] = [];
    if (props.departData) {
      props.departData.forEach((a: any) => {
        tgs.push(
          ...a.attributes.map((s: any) => {
            return {
              id: s.id,
              formName: a.name,
              key: a.id + s.id,
              formId: a.id,
              typeName: '集合',
              trigger: a.id,
              code: s.code,
              name: s.name,
            };
          }),
        );
      });
    }
    setTriggers(tgs);
  }, [props.departData]);

  if (!props.isOpen) return null;  

  return (
    <Modal
      destroyOnClose
      title={'绑定属性'}
      width={800}
      open={props.isOpen}
      bodyStyle={{ border: 'none', padding: 0, marginLeft: '32px', marginRight: '32px' }}
      onOk={() => {
        props.operateRule.showChangeData = mappingData,
        props.onClose();
      }}
      onCancel={props.onClose}>
      <Space direction="vertical" size={15} style={{ width: '100%' }}>
        <VariableMapping
          mappingData={mappingData}
          forms={props.departData}
          onChange={(v, _def) => {
            setMappingData(v);
          }}
          triggers={triggers}
        />
      </Space>
    </Modal>
  );
};

const loadOperateRule = (
  label: string,
  operateRule: any,
  operate: string, 
  departData?: { name: string; id: string; type?: string }[]
) => {
  const [isShow, setIsShow] = useState<boolean | null>(operateRule.allowShowChangeData ?? false);
  const [isOpen, setIsOpen] = useState(false);
  
  const toggleModal = () => {
    setIsOpen(!isOpen);  
  };  

  return (
    <Space>
      <CheckBox
        defaultValue={operateRule[operate] ?? false}
        onValueChange={(e) => (operateRule[operate] = e, setIsShow(e))}
      />
      {label === '仅显示变更数据' ? (
        isShow == true ? (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ width: 110 }}>{label}</div>
            <div style={{cursor: 'pointer'}} onClick={() => toggleModal()}>绑定</div>
          </div>
        ) : (
          <div style={{ width: 110 }}>{label}</div>
        )
      ):(
        <div style={{ width: 30 }}>{label}</div>
      )}
      <DataModal operateRule={operateRule} departData={departData} isOpen={isOpen} onClose={toggleModal} />
    </Space>
  );
};

export const FormOption = (props: {
  operateRule: model.FormInfo; 
  typeName: string, 
  departData?: { name: string; id: string; type?: string }[],
  work?: IWork;
}) => {
  const [center, setCenter] = useState(<></>);

  return (
    <Space>
      <Space>
        <InputNumber 
          value={props.operateRule.order}
          onChange={e => props.operateRule.order = e!}
          controls
          step={1}
          placeholder='排序'
        />
      </Space>
      {loadOperateRule('新增', props.operateRule, 'allowAdd')}
      {loadOperateRule('变更', props.operateRule, 'allowEdit')}
      {loadOperateRule('选择', props.operateRule, 'allowSelect')}
      {loadOperateRule('选择文件', props.operateRule, 'allowSelectFile')}
      {props.typeName === '子表' && loadOperateRule('仅显示变更数据', props.operateRule, 'allowShowChangeData', props.departData)}
      {props.typeName === '子表' &&
        <Space>
          <Button
            size="small"
            onClick={() => 
              setCenter(
               <ButtonConfig 
                operateRule={props.operateRule}
                work={props.work}
                finished={() => setCenter(<></>)} />
              )
            }>
            按钮配置
          </Button>
        </Space>
      }
      {center}
    </Space>
  );
};

const ShareShowRecent: React.FC<ShareShowRecentProps> = (props) => {
  const data = props.departData || [];
  return (
    <div className={cls.layout}>
      <div className={cls.title}>已选{data.length}条数据</div>
      <div className={cls.content}>
        {data.map((el: any, idx: number) => {
          return (
            <div
              style={{
                background:
                  el?.type == 'del' ? '#ffb4c4' : el?.type == 'add' ? '#beffd0' : '',
              }}
              key={el.id}
              className={`${cls.row} ${
                data.length > 1 && idx !== data.length - 1 ? cls.mgt6 : ''
              }`}>
              <div
                style={{ marginRight: 8 }}
                onClick={() => {
                  props.onClick?.call(this, el);
                }}>
                <Typography.Text
                  style={{ fontSize: 14, lineHeight: '24px', color: '#888' }}
                  title={el.name}
                  ellipsis>
                  {props.onClick ? <a>{el.name}</a> : el.name}
                </Typography.Text>
              </div>
              {props.tags?.(el.id)}
              <div
                className={cls.closeIconWarpper}
                onClick={() => {
                  props?.deleteFuc.apply(this, [el.id]);
                }}>
                <AiOutlineCloseCircle />
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default ShareShowRecent;
